﻿using Share;
using System;
using UnityEngine;

public class TimeTools
{

    private static readonly long epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
    /// <summary>
    /// 客户端时间
    /// </summary>
    /// <returns></returns>
    public static long ClientNow()
    {
        return (DateTime.UtcNow.Ticks - epoch) / 10000;
    }

    static TimeTools m_Instance;

    public static TimeTools Instance()
    {
        if (m_Instance == null)
            m_Instance = new TimeTools();
        return m_Instance;
    }

    float m_start;

    public void TimerStart()
    {
        m_start = Time.realtimeSinceStartup;
    }
    public void TimerEnd(string strLog)
    {
        XKLog.LogError(strLog + " 耗时{0}  ", (Time.realtimeSinceStartup - m_start));
        m_start = Time.realtimeSinceStartup;
    }

    /// <summary>
    /// 格式化时间显示
    /// </summary>
    /// <param name="seconds">总秒数</param>
    /// <param name="formatType">格式类型：0=时分秒,1=分秒,2=秒</param>
    /// <returns>格式化后的时间字符串</returns>
    public static string FormatTime(float seconds, int formatType = 0)
    {
        if (seconds < 0)
            return "00:00:00";

        TimeSpan timeSpan = TimeSpan.FromSeconds(seconds);

        switch (formatType)
        {
            case 0: // 时分秒
                return $"{(int)timeSpan.TotalHours:00}:{timeSpan.Minutes:00}:{timeSpan.Seconds:00}";

            case 1: // 分秒
                return $"{(int)timeSpan.TotalMinutes:00}:{timeSpan.Seconds:00}";

            case 2: // 秒
                return $"{(int)timeSpan.TotalSeconds}";

            default:
                return "00:00:00";
        }
    }

    /// <summary>
    /// 自动格式化时间显示
    /// </summary>
    /// <param name="seconds">总秒数</param>
    /// <returns>格式化后的时间字符串</returns>
    public static string FormatTimeAuto(float seconds)
    {
        if (seconds < 0)
            return "00:00";

        TimeSpan timeSpan = TimeSpan.FromSeconds(seconds);

        if (timeSpan.TotalHours >= 1)
        {
            return $"{(int)timeSpan.TotalHours:00}:{timeSpan.Minutes:00}:{timeSpan.Seconds:00}";
        }
        else if (timeSpan.TotalMinutes >= 1)
        {
            return $"{(int)timeSpan.TotalMinutes:00}:{timeSpan.Seconds:00}";
        }
        else
        {
            return $"{timeSpan.Seconds:00}";
        }
    }

    /// <summary>
    /// 获取当前日期（年:月:日）
    /// </summary>
    /// <returns>格式化后的日期字符串</returns>
    public static string FormatDay()
    {
        DateTime now = DateTime.Now;
        return $"{now.Year:0000}:{now.Month:00}:{now.Day:00}";
    }
}
